<template>
  <section>
    <el-form ref="form" :model="form" label-width="80px" :rules="rules" class="my-form">
      <el-form-item label="电话号码">
        <el-input v-model="form.mobile" type="tel" maxlength="11"></el-input>
      </el-form-item>
      <el-form-item label="密码">
        <el-input v-model="form.password" type="password" maxlength="11"></el-input>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click.prevent="onSubmit" native-type="submit">提交</el-button>
      </el-form-item>
    </el-form>
  </section>
</template>

<script>

import axios from 'axios';
import md5 from "js-md5";

export default {
  name: 'HomeView',
  data() {
    const checkMobile = (rule, value, callback) => {
        if (value == '') {
          callback(new Error('请输入电话号码'));
        } else {
          const phoneNumberRegex = /^\d{3}-\d{3}-\d{4}$/;
          if (!phoneNumberRegex.test(value)) {
            callback(new Error('电话号码不规范'));
          }
          callback();
        }
      };


    return {
      form: {
        mobile: '',
        password: ''
      },
      rules: {
        mobile: [
          { validator: checkMobile, trigger: 'blur' }
        ],
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' }
        ]
      }
    }
  },
  methods: {
    onSubmit() {
      this.$refs['form'].validate((valid) => {
        if (!valid) {
          return;
        }
      });
      axios({
        url: "http://127.0.0.1:8084/login/login",
        data: {
          mobile: this.form.mobile,
          password: md5(this.form.password)
        },
        method: "post",
      }).then(res => {
        if (res.data.code > 0) {
          const data = res.data.data;
          // console.log("token-1 = ",data);
          // HTML5的本地存储只能存储字符串，所以把data进行json序列化
          localStorage.setItem("token",data.token);
        } else {
          console.log("登录失败");
        }
      })
    }
  }

}
</script>
<style scoped lang="scss">
.my-form {
  width: 400px;
}
</style>